﻿using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;


namespace BingWallpaper
{
    public partial class FrmMain : Form
    {
        private string _strImgPath, _strCopyright, _strCopyrightLink;
        private const string StrInfoLink = "https://www.bing.com/HPImageArchive.aspx?idx=0&n=1";
        private readonly string _strSavePath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)}\BingWallpaper";

        public FrmMain() => InitializeComponent();

        #region 加载设置 相关代码

        private void FrmMain_Load(object sender, EventArgs e) => SettingClass.SetBoot();

        #endregion

        #region 壁纸更新 相关代码

        /// <summary>
        /// 时钟循环执行的事件
        /// </summary>
        private async void TmrCycle_Tick(object sender, EventArgs e)
        {
            if (tmrCycle.Interval == 1 || tmrCycle.Interval != 1000) tmrCycle.Interval = 1000;

            await InitializeWallpaper(SettingClass.GetAutoSet());
            SetUi();

            void SetUi()
            {
                if (File.Exists(_strImgPath) && !IsSameImage(BackgroundImage, Image.FromFile(_strImgPath)))
                {
                    BackgroundImage = Image.FromFile(_strImgPath);
                    lblCopyright.Text = _strCopyright;
                    tipLabel.SetToolTip(lblCopyright, _strCopyright);

                    tmrCycle.Interval = (int)(DateTime.Parse("23:59:59") - DateTime.Now).TotalMilliseconds + 1000;
                }

                bool IsSameImage(Image a, Image b)
                {
                    if (a == null || b == null) return false;
                    using (MemoryStream m1 = new MemoryStream(), m2 = new MemoryStream())
                    {
                        a.Save(m1, a.RawFormat);
                        b.Save(m2, b.RawFormat);
                        if (m1.Length != m2.Length) return false;
                        for (var i = 0; i < m1.Length; i++)
                        {
                            if (m1.ReadByte() != m2.ReadByte()) return false;
                        }
                        return true;
                    }
                }
            }
        }

        /// <summary>
        /// 初始化 WallpaperClass 类，下载并应用壁纸
        /// </summary>
        private async Task InitializeWallpaper(bool isSet)
        {
            var wallpaper = new WallpaperClass(StrInfoLink, _strSavePath);
            await wallpaper.GetInfo(isSet);
            _strImgPath = wallpaper.ImgPath;
            _strCopyright = wallpaper.Copyright;
            _strCopyrightLink = wallpaper.CopyrightLink;
        }

        #endregion

        #region UI 控件 相关代码

        private async void TsmlSetWallpaper_UIMenu_Click(object sender, EventArgs e)
            => await InitializeWallpaper(true);

        private void TsmlOpenImgLibrary_UIMenu_Click(object sender, EventArgs e)
            => Process.Start(_strSavePath);

        private void LblCopyright_Click(object sender, EventArgs e)
            => Process.Start(_strCopyrightLink);

        private void MainBingWallpaper_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason != CloseReason.UserClosing) return;
            e.Cancel = true;
            Hide();
        }

        #endregion

        #region 图标、菜单 相关代码

        private void ShowForm_Click(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left) return;
            if (Visible)
                Hide();
            else
                Show();
        }

        private void TsmlShowMain_Click(object sender, EventArgs e)
            => Show();

        private void TsmlSet_Click(object sender, EventArgs e)
            => new FrmSetting().ShowDialog();

        private void TsmlExit_Click(object sender, EventArgs e)
            => Application.Exit();

        #endregion

    }
}
